package room_event

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cast"
	global2 "longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/chat"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/internal/services/consumers/publisher"
	_const "longmen/server/pkg/common/helper/const"
	pb "longmen/server/pkg/protobuf"
)

/*
这个是客户端主播发消息要删
*/
func handlingClearMessage(c *chat.ClientUser, b []byte) (ret *pb.CallbackResp, errRes error) {
	ret = &pb.CallbackResp{
		ActionStatus: imsdk.OKActionStatus,
		ErrorCode:    imsdk.TIM_CODE_OK,
	}
	rep := &messages2.ReplyMessage{
		Type:    messages2.ClearReplyMessageType,
		Code:    0,
		Message: "",
	}

	req := messages2.ClearMessage{}
	err := json.Unmarshal(b, &req)
	if err != nil {
		rep.Code = 100199
		rep.Message = fmt.Sprintf("invalid message struct, %s", err)
		return utils.CallbackFailResp(rep, rep.Message), nil
	}

	GetChatHistory(req.RoomId).DeleteChatHistory(int64(req.ChatId), messages2.ClearHisChatType)
	pubMsg := &messages2.ClearChatMessage{
		SentMessageStruct: messages2.SentMessageStruct{Type: messages2.RoomClearChatType},
		ChatId:            req.ChatId,
		UserId:            req.UserId,
		RoomId:            req.RoomId,
	}
	//apiCache.PushAny(pubMsg, messages.ClearChatChannel)
	err = global2.PublisherTxChat.BroadCast(publisher.ClearChat, pubMsg)
	if err != nil {
		global2.Log.Errorf("广播消息推送失败: %v", err)
	}
	cache.NewRoomHeat(req.RoomId).SetDec(_const.PopMsgCount, 1)
	return utils.CallbackOkAndExt(rep, cast.ToString(req.RoomId)), nil //返回改过的rep
}
